using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Reflection;

namespace Clarius.WindowsLive.Writer.CrossPostPlugin
{
	public class XhtmlResolver : XmlResolver
	{
		Dictionary<Uri, Stream> dtds = new Dictionary<Uri, Stream>();

		public XhtmlResolver()
		{
			string baseName = Path.GetFileNameWithoutExtension(
					this.GetType().Assembly.ManifestModule.FullyQualifiedName);
			Assembly asm = this.GetType().Assembly;

			dtds.Add(
				new Uri("urn:-//W3C//DTD XHTML 1.0 Strict//EN"),
				asm.GetManifestResourceStream(baseName + ".xhtml1-strict.dtd"));
			dtds.Add(
				new Uri("urn:xhtml-lat1.ent"),
				asm.GetManifestResourceStream(baseName + ".xhtml-lat1.ent"));
			dtds.Add(
				new Uri("urn:xhtml-special.ent"),
				asm.GetManifestResourceStream(baseName + ".xhtml-special.ent"));
			dtds.Add(
				new Uri("urn:xhtml-symbol.ent"),
				asm.GetManifestResourceStream(baseName + ".xhtml-symbol.ent"));
		}

		public override System.Net.ICredentials Credentials
		{
			set { throw new Exception("The method or operation is not implemented."); }
		}

		public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
		{
			Stream s;
			if (dtds.TryGetValue(absoluteUri, out s))
			{
				return s;
			}

			return null;
		}

		public override Uri ResolveUri(Uri baseUri, string relativeUri)
		{
			return new Uri("urn:" + relativeUri);
			//foreach (XmlResource resource in this._knownResources)
			//{
			//   //TODO: REVIEW: EndsWith is propably not suitable here. We should probably check the full string or "system ID"
			//   Uri relUri = new Uri("urn:" + relativeUri);
			//   if (resource.XmlUri.AbsolutePath.EndsWith(relUri.AbsolutePath))
			//   {
			//      Trace.WriteLine(string.Format("CustomXmlResolver.ResolveUri: '{0}' Resolved succsfully.", relativeUri));
			//      return resource.XmlUri;
			//   }
			//}

			//return base.ResolveUri(baseUri, relativeUri);
		}
	}
}
